﻿
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text.Json.Nodes;
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Memory;
using VueAdminService.VO;
using VueAdminService.DTO;
using VueAdminService.Attributes;
using VueAdminService.Utils;
namespace VueAdminService.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	[TokenRequired]
	public class RoleController : BaseController
	{
		protected readonly IConfiguration _configuration;
		public RoleController(IConfiguration configuration, IServiceProvider serviceProvider) : base(serviceProvider)
		{
			_configuration = configuration;
		}
		/// <summary>
		/// 角色分页列表
		/// </summary>
		/// <param name="page"></param>
		/// <param name="limit"></param>
		/// <param name="keyword"></param>
		/// <returns></returns>
		[HttpGet("pagelist")]
		public ResponsePageResult<List<ResponseRoleVO>> GetList([FromQuery] int pageIndex, [FromQuery] int pageSize, [FromQuery] string? keyword)
		{
			try
			{
				int total = 0;
				var list = _dbClient.Queryable<RoleDTO>()
					.WhereIF(!string.IsNullOrWhiteSpace(keyword), r => r.RoleName.Contains(keyword) || r.Bak.Contains(keyword))
					.Where(u => u.RoleId != _configuration["AppConfig:SystemId"])//过滤掉内置角色
					.OrderByDescending(r => r.RoleId)
					.Select<ResponseRoleVO>()
					.ToPageList(pageIndex, pageSize, ref total);

				foreach (ResponseRoleVO item in list)
				{
					item.Menus = _dbClient.Queryable<PermissionDTO>()
						.InnerJoin<RolePermissionDTO>((p, r) => p.PermissionId == r.PermissionId && r.RoleId == item.RoleId)
						.Where((p, r) => p.Type == "menu")
						.ToTree(d => d.Children, d => d.ParentId, null);
					item.Operators = _dbClient.Queryable<PermissionDTO>()
						.InnerJoin<RolePermissionDTO>((p, r) => p.PermissionId == r.PermissionId && r.RoleId == item.RoleId)
						.Where((p, r) => p.Type == "operator")
						.ToTree(d => d.Children, d => d.ParentId, null);
				}

				return SuccessPageResult<List<ResponseRoleVO>>(list, total);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取角色列表失败");
				return ErrorPageResult<List<ResponseRoleVO>>("获取角色列表失败");
			}

		}
		/// <summary>
		/// 角色列表
		/// </summary>		
		/// <returns></returns>
		[HttpGet("list")]
		public ResponseResult<List<ResponseRoleVO>> GetList()
		{
			try
			{
				var list = _dbClient.Queryable<RoleDTO>()
					.Where(u => u.RoleId != _configuration["AppConfig:SystemId"])//过滤掉内置角色
					.OrderByDescending(r => r.RoleId)
					.Select<ResponseRoleVO>()
					.ToList();

				return SuccessResult<List<ResponseRoleVO>>(list);
			}
			catch (Exception ex)
			{
				LogError(ex, "获取角色列表失败");
				return ErrorResult<List<ResponseRoleVO>>("获取角色列表失败", null);
			}

		}
		/// <summary>
		/// 添加角色
		/// </summary>
		/// <param name="vo">请求实体</param>
		/// <returns></returns>
		[HttpPost]
		public ResponseResult<bool> Add([FromBody] RequestAddRoleVO vo)
		{
			try
			{
				_dbClient.Ado.BeginTran();
				//插入角色
				string roleId = SnowFlakeSingle.Instance.NextId().ToString();
				_dbClient.Insertable<RoleDTO>(new RoleDTO()
				{
					RoleId = roleId,
					RoleName = vo.RoleName,
					Bak = vo.Bak
				}).ExecuteCommand();
				//插入角色权限				
				if (vo.PermissionIds.Count > 0)
				{
					List<RolePermissionDTO> rolePermissions = new List<RolePermissionDTO>();
					foreach (string id in vo.PermissionIds)
					{
						rolePermissions.Add(new RolePermissionDTO()
						{
							RolePermissionId = SnowFlakeSingle.Instance.NextId().ToString(),
							RoleId = roleId,
							PermissionId = id,
						});
					}
					_dbClient.Insertable(rolePermissions).ExecuteCommand();
				}

				_dbClient.Ado.CommitTran();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				_dbClient.Ado.RollbackTran();
				LogError(ex, "添加角色失败");
				return ErrorResult("添加角色失败", false);
			}
		}
		/// <summary>
		/// 删除角色
		/// </summary>
		/// <param name="roleId">角色Id</param>
		/// <returns></returns>
		[HttpDelete("{roleId}")]
		public ResponseResult<bool> Delete(string roleId)
		{
			if (roleId == _configuration["AppConfig:SystemId"])
			{
				return FailedResult("内置角色不能删除", false);
			}
			try
			{
				_dbClient.Ado.BeginTran();
				//删除角色
				_dbClient.Deleteable<RoleDTO>(r => r.RoleId == roleId).ExecuteCommand();
				//删除角色权限
				_dbClient.Deleteable<RolePermissionDTO>(r => r.RoleId == roleId).ExecuteCommand();

				_dbClient.Ado.CommitTran();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				_dbClient.Ado.RollbackTran();
				LogError(ex, "删除角色失败");
				return FailedResult("删除角色失败", false);
			}
		}
		/// <summary>
		/// 修改角色
		/// </summary>
		/// <param name="vo">修改实体</param>
		/// <returns></returns>
		[HttpPut]
		public ResponseResult<bool> Update([FromBody] RequestEditRoleVO vo)
		{
			if (string.IsNullOrWhiteSpace(vo.RoleId))
			{
				return FailedResult("角色Id不能为空", false);
			}
			try
			{
				_dbClient.Ado.BeginTran();
				//修改角色
				_dbClient.Updateable<RoleDTO>(new RoleDTO()
				{
					RoleId = vo.RoleId,
					RoleName = vo.RoleName,
					Bak = vo.Bak,
				}).ExecuteCommand();
				//删除原角色权限
				_dbClient.Deleteable<RolePermissionDTO>(r => r.RoleId == vo.RoleId).ExecuteCommand();

				//插入新的角色权限
				if (vo.PermissionIds.Count > 0)
				{
					List<RolePermissionDTO> rolePermissions = new List<RolePermissionDTO>();
					foreach (string id in vo.PermissionIds)
					{
						rolePermissions.Add(new RolePermissionDTO()
						{
							RolePermissionId = SnowFlakeSingle.Instance.NextId().ToString(),
							RoleId = vo.RoleId,
							PermissionId = id,
						});
					}
					_dbClient.Insertable(rolePermissions).ExecuteCommand();
				}
				_dbClient.Ado.CommitTran();
				return SuccessResult(true);
			}
			catch (Exception ex)
			{
				_dbClient.Ado.RollbackTran();
				LogError(ex, "修改角色失败");
				return FailedResult("修改角色失败", false);
			}
		}
	}
}
